package com.um.jdy.mp.station.manager;

import com.um.jdy.common.device.code.DeviceCode;
import com.um.jdy.common.device.entity.dto.StationSharingDTO;
import com.um.jdy.common.device.entity.po.Station;
import com.um.jdy.common.device.entity.po.StationSharing;
import com.um.jdy.common.device.service.StationService;
import com.um.jdy.common.device.service.StationSharingService;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.mp.station.entity.dto.SharingDTO;
import com.um.jdy.mp.station.entity.vo.SharingMerchantVO;
import com.um.jdy.mp.station.entity.vo.StationSharingItemVO;
import com.um.jdy.mp.station.entity.vo.StationSharingUserVO;
import com.um.jdy.mp.station.entity.vo.UserSharingItemVO;
import com.um.jdy.mp.user.service.SessionUserService;
import com.um.springboot.starter.code.CommonCode;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.ListParams;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * @author cs
 * 日期 2023/6/22
 * 版权所有 广州优匠科技有限公司
 */
@Service
@Slf4j
public class StationSharingManager extends BaseManager<StationSharingService> {

    @Autowired
    SessionUserService sessionUserService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    StationService stationService;

    public Response<Page<StationSharingItemVO>> getPage(PageParams params) {
        Page<StationSharingItemVO> page = new Page<>();
        page.setPageNo(params.getPageNo());
        page.setPageSize(params.getPageSize());
        params.getCondition().put("s.com_id", getComId());
        params.getCondition().put("s.platform_merchant_id", sessionUserService.getTokenUserId());

        page = stationService.getCMSViewModelPageBySqlName(page, "get_station_page", "get_station_count",
                StationSharingItemVO.class, params.getProperties(), params.getValues(), params.getRangeEntitys(), params.getOrderNames(), params.getSortOns());
        page.getResult().forEach(row->{
            row.setStationSharings(service.getViewModelList("get_sharing_station_list", SharingMerchantVO.class,
                    new Object[]{getComId(), row.getDeviceStationId()}));
        });
        return Response.success(page);
    }

    /**
     * 分成人员列表
     *
     * @param stationId
     * @return
     */
    public Response<List<UserSharingItemVO>> getSharingListByParentId(String stationId) {

        checkPermission(stationId);

        List<UserSharingItemVO> list = service.getViewModelList("get_station_sharing_list_by_parentid", UserSharingItemVO.class,
                new Object[]{stationId,getComId(),sessionUserService.getTokenUserId(),getComId()});
        return Response.success(list);
    }

    public Response<List<StationSharingUserVO>> getUserList(ListParams params) {
        params.getCondition().put("m.com_id", getComId());
        params.getCondition().put("m.parent_id", sessionUserService.getTokenUserId());
        List<StationSharingUserVO> list = service.getCMSViewModelListBySqlName("get_sharing_user_list", StationSharingUserVO.class,
                params.getProperties(), params.getValues(), params.getRangeEntitys(), params.getOrderNames(), params.getSortOns());
        return Response.success(list);
    }

    public Response<Page<StationSharingUserVO>> getUserPage(PageParams params) {
        Page<StationSharingUserVO> page = new Page<>();
        page.setPageNo(params.getPageNo());
        page.setPageSize(params.getPageSize());
        params.getCondition().put("m.com_id", getComId());
        params.getCondition().put("m.parent_id", sessionUserService.getTokenUserId());
        page = service.getCMSViewModelPageBySqlName(page, "get_sharing_user_page", "get_sharing_user_count", StationSharingUserVO.class,
                params.getProperties(), params.getValues(), params.getRangeEntitys(), params.getOrderNames(), params.getSortOns());
        return Response.success(page);
    }

    @Transactional
    public Response saveEntity(SharingDTO dto) {

        checkPermission(dto.getDeviceStationId());

        int sum = 0;
        for(StationSharingDTO item : dto.getList()){
            sum += item.getCommissionRate();
        }

        Station station = stationService.getEntity(dto.getDeviceStationId());
        if(station == null){
            throw new ServiceException(DeviceCode.NoStation);
        }

        if(sum > station.getCommissionRate().intValue()){
            throw new ServiceException(PartnersCode.RateNotLargeThanStation);
        }

        //先删除
        service.delete("device_station_id",dto.getDeviceStationId());

        int sortNo = 1;
        for(StationSharingDTO stationSharingDTO : dto.getList()){

            checkMerchantPermission(stationSharingDTO.getPlatformMerchantId());

            StationSharing entity = UMBeanUtils.copyBean(stationSharingDTO,StationSharing.class);
            entity.setCreateTime(new Date());
            entity.setDeviceStationId(dto.getDeviceStationId());
            entity.setSortNo(sortNo);
            sortNo ++;
            service.addEntity(entity);
        }
        return Response.success();
    }

    /**
     * 删除分账用户
     *
     * @param id
     * @return
     */
    public Response delete(String id) {
        StationSharing stationSharing = service.getEntity(new String[]{"device_station_sharing_id"}, new Object[]{id});
        if (stationSharing == null) {
            return Response.failed("分账用户不存在，删除失败！");
        }

        checkPermission(stationSharing.getDeviceStationId());

        service.delete(stationSharing.getDeviceStationSharingId());

        return Response.success();
    }

    /**
     * 校验数据权限
     * @param id
     */
    private void checkPermission(String id){
        Station station = stationService.getEntity(id);
        if(station == null)
            throw new ServiceException(DeviceCode.NoStation);

        if(!StringUtil.equals(sessionUserService.getTokenUserId(),station.getPlatformMerchantId()))
            throw new ServiceException(CommonCode.NoDataPermission);
    }

    /**
     * 校验数据权限
     * @param id
     */
    private void checkMerchantPermission(String id){
        Merchant merchant = merchantService.getEntity(id);
        if(merchant == null)
            throw new ServiceException(PartnersCode.PartnersNotExist);

        if(!StringUtil.equals(sessionUserService.getTokenUserId(),merchant.getParentId()))
            throw new ServiceException(CommonCode.NoDataPermission);
    }
}
